package com.windoent.yugioh.ui.fragment.saishi.end;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.mobstat.StatService;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.windoent.yugioh.R;
import com.windoent.yugioh.adapter.brvah.PanFaAdapter;
import com.windoent.yugioh.adapter.brvah.PanFaJudgeAdapter;
import com.windoent.yugioh.base.BaseFragment;
import com.windoent.yugioh.bean.PanFaListData;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.SimpleUtils;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.widget.RoundImageView;
import com.windoent.yugioh.widget.dialog.PanFaDetailsDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;

import java.util.List;

import okhttp3.Call;

/**
 * author : robert
 * date   : 2021/5/21 15:56
 * desc   :
 */
public class EndedPanFaFragment extends BaseFragment {
    private RecyclerView mRecyclerViewPanfa;
    private SmartRefreshLayout mSmartLayout;

    private String limit = Constants.PAGETEN;
    private int mCount = 1;
    private PanFaAdapter adapter;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_saishi_ended_panfa;
    }

    public static EndedPanFaFragment newsInstance(String id) {
        //创建 Bundle
        EndedPanFaFragment fragment = new EndedPanFaFragment();
        Bundle lBundle = new Bundle();
        lBundle.putString("id", id);
        fragment.setArguments(lBundle);
        return fragment;
    }

    @Override
    protected void initEventAndData() {
        initView();
        initData();
    }

    private void initData() {
        initPanFaAdapter();
    }

    private void initRefreshData(String id) {
        //下拉刷新
        mSmartLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                fresh(id);
            }
        });
        //加载更多
        mSmartLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//                loadMore(id);
            }
        });
    }

    private void loadMore(String text) {
        mCount = mCount + 1;
        getAllPanFaList(text, mCount + "", limit, false);
    }

    private void fresh(String text) {
        mCount = 1;
        getAllPanFaList(text, mCount + "", limit, true);
    }

    private void initView() {
        mRecyclerViewPanfa = (RecyclerView) mView.findViewById(R.id.recycler_view_panfa);
        mSmartLayout = (SmartRefreshLayout) mView.findViewById(R.id.smart_layout);
    }

    //裁判
    private void initJudgeAdapter(RecyclerView mRecyclerViewJudge, List<PanFaListData.DataBean.RefereeBean> refereeBeans) {
        mRecyclerViewJudge.setLayoutManager(new GridLayoutManager(mContext, 5));
        PanFaJudgeAdapter adapter = new PanFaJudgeAdapter();
        adapter.setEmptyView(LayoutInflater.from(mContext).inflate(R.layout.recycler_view_empty, mRecyclerViewJudge, false));
        adapter.setAnimationEnable(false);
        adapter.setNewInstance(refereeBeans);
        mRecyclerViewJudge.setNestedScrollingEnabled(false);
        mRecyclerViewJudge.setAdapter(adapter);

    }

    //判罚记录
    private void initPanFaAdapter() {
        mRecyclerViewPanfa.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new PanFaAdapter();
        adapter.setEmptyView(LayoutInflater.from(mContext).inflate(R.layout.recycler_view_empty, mRecyclerViewPanfa, false));
        adapter.setAnimationEnable(false);
        mRecyclerViewPanfa.setNestedScrollingEnabled(false);
        mRecyclerViewPanfa.setAdapter(adapter);
        adapter.addChildClickViewIds(R.id.tv_details);
        adapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> baseQuickAdapter, @NonNull View view, int position) {
                List<PanFaListData.DataBean.ResBean> data = adapter.getData();
                PanFaListData.DataBean.ResBean resBean = data.get(position);
                if (resBean != null) {
                    showDetailsPanfaDialog(resBean.getRemark());
                }
            }
        });
    }

    //主裁判
    private void addMainJudgeHeader(PanFaAdapter adapter, PanFaListData.DataBean.RefereeBean item) {
        if (isAdded() && getActivity() != null) {
            View headView = getLayoutInflater().inflate(R.layout.head_rv_view_panfa_main_judge_header, (ViewGroup) mRecyclerViewPanfa.getParent(), false);
            RoundImageView mIvAvatarMainJudge = (RoundImageView) headView.findViewById(R.id.iv_avatar_main_judge);
            TextView mTvNameMainJudge = (TextView) headView.findViewById(R.id.tv_name_main_judge);
            TextView mTvIdMainJudge = (TextView) headView.findViewById(R.id.tv_id_main_judge);
            if (item != null) {
                setText(mTvNameMainJudge, item.getNickname());
                setText(mTvIdMainJudge, getString(R.string.string_user_info_id) + item.getRefereeViewId() + "");
                SimpleUtils.loadImageForView(mContext, mIvAvatarMainJudge, item.getAvatar(), R.drawable.img_official_avatar_android);
            }
            if (adapter != null) {
                adapter.addHeaderView(headView);
                adapter.setHeaderWithEmptyEnable(true);
                if (adapter.hasEmptyView()) {
                    adapter.setUseEmpty(false);
                }
            }
        }
    }

    //裁判
    private void addJudgeRvHeader(PanFaAdapter adapter, List<PanFaListData.DataBean.RefereeBean> refereeBeans) {
        if (isAdded() && getActivity() != null) {
            View headView = getLayoutInflater().inflate(R.layout.head_rv_view_panfa_rv_judge_header, (ViewGroup) mRecyclerViewPanfa.getParent(), false);
            RecyclerView mRecyclerViewJudge = (RecyclerView) headView.findViewById(R.id.recycler_view_judge);
            initJudgeAdapter(mRecyclerViewJudge, refereeBeans);
            if (adapter != null) {
                adapter.addHeaderView(headView);
                adapter.setHeaderWithEmptyEnable(true);
                if (adapter.hasEmptyView()) {
                    adapter.setUseEmpty(false);
                }
            }
        }
    }

    //详情
    private void showDetailsPanfaDialog(String s) {
        PanFaDetailsDialog dialog = new PanFaDetailsDialog(mContext);
        dialog.setContentStr(s);
        dialog.show();
    }

    //添加判罚头标题
    private void addRvTiltleHeader(PanFaAdapter adapter) {
        if (isAdded() && getActivity() != null) {
            View headView = getLayoutInflater().inflate(R.layout.head_rv_view_panfa_title, (ViewGroup) mRecyclerViewPanfa.getParent(), false);
            if (adapter != null) {
                adapter.addHeaderView(headView);
                adapter.setHeaderWithEmptyEnable(true);
                if (adapter.hasEmptyView()) {
                    adapter.setUseEmpty(false);
                }
            }
        }
    }

    //判罚记录文字
    private void addRvTiltleTextHeader(PanFaAdapter adapter) {
        if (isAdded() && getActivity() != null) {
            View headView = getLayoutInflater().inflate(R.layout.head_rv_view_panfa_record_title, (ViewGroup) mRecyclerViewPanfa.getParent(), false);
            if (adapter != null) {
                adapter.addHeaderView(headView);
                adapter.setHeaderWithEmptyEnable(true);
                if (adapter.hasEmptyView()) {
                    adapter.setUseEmpty(true);
                }
            }
        }
    }

    //判罚
    private void getAllPanFaList(String id, String page, String limit, boolean fresh) {
        showLoadingDialog("");
        PhoneLive.getAllPanFaList(getUserToken(), id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
                freshFail(fresh);
            }

            @Override
            public void onResponse(String response, int idres) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            PanFaListData fromJson = gson.fromJson(response, PanFaListData.class);
                            if (fromJson != null) {
                                PanFaListData.DataBean data = fromJson.getData();
                                if (data != null) {
                                    if (fresh) {
                                        addHeader(data);
                                    }
                                    List<PanFaListData.DataBean.ResBean> res = data.getRes();
                                    if (res != null) {
                                        if (fresh) {
                                            adapter.setNewInstance(res);
                                            mSmartLayout.finishRefresh(true);
                                        } else {
                                            adapter.addData(res);
                                            adapter.notifyDataSetChanged();
                                            mSmartLayout.finishLoadMore(true);
                                        }
                                    } else freshFail(fresh);
                                } else freshFail(fresh);
                            } else freshFail(fresh);
                        } else freshFail(fresh);
                    } catch (JSONException e) {
                        freshFail(fresh);
                        e.printStackTrace();
                    }
                } else {
                    freshFail(fresh);
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //添加头布局
    private void addHeader(PanFaListData.DataBean res) {
        assert adapter != null;
        if (adapter.getHeaderLayoutCount() > 0) {
            adapter.removeAllHeaderView();
        }
        //referee主裁判列表
        List<PanFaListData.DataBean.RefereeBean> umpire = res.getReferee();
        if (umpire != null && umpire.size() > 0) {
            PanFaListData.DataBean.RefereeBean refereeBean = umpire.get(0);
            if (refereeBean != null) {
                addMainJudgeHeader(adapter, refereeBean);
            }
        }
        List<PanFaListData.DataBean.RefereeBean> referee = res.getUmpire();
        if (referee != null && referee.size() > 0) {
            addJudgeRvHeader(adapter, referee);
        }
        List<PanFaListData.DataBean.ResBean> list = res.getRes();
        addRvTiltleTextHeader(adapter);
        if (list != null && list.size() > 0) {
            addRvTiltleHeader(adapter);
        }
    }

    //刷新失败
    private void freshFail(boolean fresh) {
        if (fresh) {
            adapter.setNewInstance(null);
            mSmartLayout.finishRefresh(false);
        } else {
            mSmartLayout.finishLoadMore(false);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (getActivity() != null) {
            // 页面埋点
            StatService.onPageEnd(getActivity(), "赛事进行中判罚tab");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getActivity() != null) {
            // 页面埋点
            StatService.onPageStart(getActivity(), "赛事进行中判罚tab");
        }
        getDetailsId();
    }

    private String id;

    //获取activity传值id
    private void getDetailsId() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            id = bundle.getString("id");
            initRefreshData(id);
            fresh(id);
        }
    }
}
